package com.shop.controller;

import com.alibaba.fastjson.JSON;
import com.shop.entity.Goods;
import com.shop.entity.ShowPageT;
import com.shop.servlet.impl.GoodsServletImpl;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Part;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * com.shop.controller文档说明
 *
 * @author Angluzha
 * @version 2022/9/15
 */
@WebServlet("/goods/*")
@MultipartConfig
public class GoodsController extends  BaseController<Goods>{
    {
        servlet = new GoodsServletImpl();
    }

    public String save(Goods goods){
        try {
            Part part = req.getPart("pnguri");
            String pnguri = part.getSubmittedFileName();

            goods.setPnguri(pnguri);
            File file = new File("D:/Java/images/"+pnguri);
            IOUtils.copy(part.getInputStream(),new FileOutputStream(file));
            servlet.insert(goods);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return redirect("/goods/selectAll");
    }

    public String delete(Goods goods){
        servlet.deleteById(goods.getId());
        return redirect("/goods/selectAll");
    }

    public String update(Goods goods){
        servlet.update(goods);
        return redirect("/goods/selectAll");
    }

    public String selectAll(){
        ShowPageT<Goods> pageT = (ShowPageT<Goods>) req.getAttribute("pageT");
        page(pageT,"/goods/selectAll");
        System.out.println(pageT);
        return forward("/back/goods/goodsList.jsp");
    }
    public String delCheck(){
        try {
            String line = req.getReader().readLine();
            List<Integer> userList = JSON.parseArray(line, Integer.class);
            if(servlet.delCheck(userList)){
                return writeWeb("200");
            }else {
                return writeWeb("100");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
